# -*- encoding:utf-8 -*-
# __author__ = 'chenyongbing'
# __poject__ = 'ops_platform'
# __datetime__ = '2022/6/13'
# __name__ = 'handles.py'
from utils.tapd_helper import TapdHelper
from apps.system.handles import get_config_by_group
from utils.kubernetes_helper import KubeClient
from apps.resource.models import *
import re
import requests
import time
import datetime
from django.core.cache import cache
import json
# Create your code here.


def get_tapd_workspaces():
    params = get_config_by_group(group='tapd')
    tapd = TapdHelper(**params)
    workspace_ids = params.get('workspace_ids','').split(',')
    workspaces = []
    for workspace in tapd.workspaces().get('data', []):
        id = workspace.get('Workspace', {}).get('id')
        if id not in workspace_ids: continue

        workspaces.append({
            'id': id,
            'name': workspace.get('Workspace', {}).get('name')
        })
    return workspaces

def get_tapd_workspace_stories(workspace_id, deploy_date, status=''):
    params = get_config_by_group(group='tapd')
    deploy_date_key = params.get('deploy_date_key', 'custom_field_eight')
    service_key = params.get('service_key', 'custom_field_14')
    tapd = TapdHelper(**params)
    p = {'workspace_id': workspace_id,
         deploy_date_key: deploy_date,
         'status': status,
         'limit': 200}
    stories = []
    for story in tapd.stories(**p).get('data', []):
        stories.append({
            'id': story.get('Story',{}).get('id'),
            'name': story.get('Story',{}).get('name'),
            'deploy_date': story.get('Story',{}).get(deploy_date_key),
            'owner': story.get('Story',{}).get('owner'),
            'developer': story.get('Story',{}).get('developer'),
            'status': story.get('Story',{}).get('status'),
            'services': story.get('Story', {}).get(service_key, '').split('|')
        })
    return stories


def get_tapd_workspace_bugs(workspace_id, deploy_date, status=''):
    params = get_config_by_group(group='tapd')
    deploy_date_key = 'custom_field_four'
    service_key = 'custom_field_five'
    tapd = TapdHelper(**params)
    p = {'workspace_id': workspace_id,
         deploy_date_key: deploy_date,
         'custom_field_three': 'Prod',
         'limit': 200}
    bugs = []
    for bug in tapd.bugs(**p).get('data', []):
        bugs.append({
            'id': bug.get('Bug',{}).get('id'),
            'name': bug.get('Bug',{}).get('title'),
            'deploy_date': bug.get('Bug',{}).get(deploy_date_key),
            'owner': bug.get('Bug',{}).get('reporter'),
            'developer': bug.get('Bug',{}).get('current_owner'),
            'status': bug.get('Bug',{}).get('status'),
            'services': bug.get('Bug', {}).get(service_key, '').split('|')
        })
    return bugs


def get_tapd_workspace_services(workspace_id, deploy_date,status=''):
    params = get_config_by_group(group='tapd')
    deploy_date_key = params.get('deploy_date_key', 'custom_field_eight')
    service_key = params.get('service_key', 'custom_field_14')
    tapd = TapdHelper(**params)
    p = {'workspace_id': workspace_id,
         deploy_date_key: deploy_date,
         'status': status,
         'limit': 200}
    services = []
    for story in tapd.stories(**p).get('data', []):
        for service in story.get('Story', {}).get(service_key, '').split('|'):
            if service and service not in services:
                services.append(service)
    p = {'workspace_id': workspace_id,
         'custom_field_four': deploy_date,
         'custom_field_three': 'Prod',
         'limit': 200}
    for bug in tapd.bugs(**p).get('data', []):
        for service in bug.get('Bug', {}).get('custom_field_five', '').split('|'):
            if service and service not in services:
                services.append(service)
    blacklist = params.get('blacklist', '').split(',')
    nopipelineservice = list( set(services) & set(blacklist))
    pipelineservices = list(set(services) - set(blacklist))
    nopipelineservice.sort()
    pipelineservices.sort()
    return {'pipeline': pipelineservices, 'blacklist': nopipelineservice}

def get_tapd_workspace_tcases(workspace_id, created):
    params = get_config_by_group(group='tapd')
    tapd = TapdHelper(**params)
    page = 1
    limit = 200
    alldata = []
    while 1:
        datas = tapd.tcases(workspace_id=workspace_id, created=created, limit=limit, page=page)
        alldata += datas.get('data')
        if len(datas.get('data', [])) == limit:
            page += 1
        else:
            break
    return alldata

def stat_tapd_workspace_tcases_by_creator(workspace_id, created):
    statdata = {}
    alldata = get_tapd_workspace_tcases(workspace_id=workspace_id, created=created)
    for data in alldata:
        creator = data.get('Tcase', {}).get('creator')
        ui_auto_count = data.get('Tcase', {}).get('custom_field_1')
        api_auto_count = data.get('Tcase', {}).get('custom_field_2')
        if not creator: continue
        if creator not in statdata.keys():
            statdata[creator] = {'new': 0, 'ui': 0, 'api': 0, 'owner': creator}
        if ui_auto_count:
            statdata[creator]['ui']+=1
        if api_auto_count:
            statdata[creator]['api']+=1
        statdata[creator]['new']+=1
    return statdata
def get_tapd_workspace_tplans(workspace_id, end_date):
    params = get_config_by_group(group='tapd')
    tapd = TapdHelper(**params)
    page = 1
    limit = 200
    fields = ','.join(['id', 'name', 'owner', 'type', 'custom_field_2', 'custom_field_3','end_date'])
    alldata = []
    # datas = tapd.tplans(workspace_id=workspace_id, end_date=end_date, page=page, limit=limit)
    # return  datas
    if re.search('~', end_date):
        end_date_s, end_date_e = end_date.split('~')
        end_date_list = []
        days = (datetime.datetime.strptime(end_date_e, '%Y-%m-%d') - datetime.datetime.strptime(end_date_s, '%Y-%m-%d')).days
        i = 0
        while i <= days:
            d = (datetime.datetime.strptime(end_date_s, '%Y-%m-%d')  + datetime.timedelta(i)).strftime('%Y-%m-%d')
            end_date_list.append(d)
            i+=1
    else:
        end_date_list = [end_date]
    for e in end_date_list:
        page = 1
        while 1:
            datas = tapd.tplans(workspace_id=workspace_id, end_date=e, page=page, limit=limit, fields=fields)
            alldata += datas.get('data', [])
            if len(datas.get('data', [])) == limit:
                page += 1
            else:
                break
    return alldata


def get_tapd_tplan_tcases_count(workspace_id, tplan_id):
    params = get_config_by_group(group='tapd')
    tapd = TapdHelper(**params)
    page = 1
    limit = 200
    total = 0
    while 1:
        datas = tapd.tplan_tcases(workspace_id=workspace_id, test_plan_id=tplan_id, page=page, limit=limit)
        total+=len(datas.get('data', []))
        if len(datas.get('data', [])) == limit:
            page += 1
        else:
            break
    return total


def get_tapd_tplan_tcases_count_cache(workspace_id, tplan_id):
    key = 'ops:eff:tapd:{}:tplan:{}:tcases'.format(workspace_id, tplan_id)
    value = cache.get(key)
    if value == None:
        value = get_tapd_tplan_tcases_count(workspace_id,tplan_id)
        exp_time = 86400 - int(time.time()%86400)
        cache.set(key, value, exp_time)


    return int(value)

def stat_tapd_workspace_tplans_by_creator(workspace_id, end_date):
    statdata = {}
    alldata = get_tapd_workspace_tplans(workspace_id=workspace_id, end_date=end_date)
    for data in alldata:
        owners = data.get('TestPlan', {}).get('owner')
        tplan_id = data.get('TestPlan', {}).get('id')
        tcase_count = get_tapd_tplan_tcases_count_cache(workspace_id, tplan_id)
        mancount = data.get('TestPlan', {}).get('custom_field_3') or 0
        type = data.get('TestPlan', {}).get('type')
        manhour = round(float(data.get('TestPlan', {}).get('custom_field_2') or 0), 1)
        hghour = manhour if re.search('回归', type) else 0
        if not owners: continue
        for owner in owners.split(';'):
            if not owner:continue
            if owner not in statdata.keys():
                statdata[owner] = {
                    'count': 0,
                    'manhour': 0,
                    'hghour': 0,
                    'owner': owner
                }
            total_count = tcase_count + int(mancount)
            statdata[owner]['count'] += total_count
            statdata[owner]['manhour'] += manhour
            statdata[owner]['hghour'] += hghour
    return statdata

def stat_tapd_workspace_tplans_and_tcases(workspace_id, created):
    tcases = stat_tapd_workspace_tcases_by_creator(workspace_id, created)
    tplans = stat_tapd_workspace_tplans_by_creator(workspace_id, end_date=created)
    owners = list(set(list(tcases.keys()) + list(tplans.keys()) ))
    uplans = {}
    for owner in owners:
        uplan = {'count': 0, 'api': 0, 'ui': 0, 'hghour': 0, 'manhour': 0, 'new': 0}
        tplan = tplans.get(owner, {})
        tcase = tcases.get(owner, {})
        uplan.update(tcase)
        uplan.update(tplan)
        uplan.update({'api_rate': "{:.0%}".format(0) if uplan.get('new', 0) == 0 else "{:.0%}".format(uplan.get('api', 0)/uplan.get('new', 1))})
        uplan.update({'ui_rate': "{:.0%}".format(0) if uplan.get('new', 0) == 0 else "{:.0%}".format(uplan.get('ui', 0)/uplan.get('new', 1))})
        uplans[owner] = uplan
    return uplans

def get_imagediff_kubes():
    config = get_config_by_group(group='imagediff')
    kubes = config.get('kubes', '')
    data = []
    for kubeid in kubes.split(','):
        kubeobj = Kubernetes.objects.get(id=kubeid)
        data.append({
            'id': kubeobj.id,
            'name': kubeobj.name
        })
    return data


def get_imagediff_list(kubes=[] , samehide=0):
    config = get_config_by_group(group='imagediff')
    kubes = kubes or config.get('kubes', '').split(',')
    namespace = config.get('namespace', '')
    blacklist = config.get('blacklist', '').split(',')
    deploydict = {}
    for kubeid in kubes:

        kubeobj = Kubernetes.objects.get(id=kubeid)
        kubeconfig = kubeobj.kubeconfig
        kubecli = KubeClient(kubeid, kubeconfig)
        deploylist = kubecli.get_namespaced_deployment_image_tags(namespace=namespace)
        deploydict[kubeid] = deploylist

    deploynames = []

    for deploylist in deploydict.values():
        deploynames = list(set(deploynames).union(set(deploylist.keys())))
    datas = []
    for deployname in deploynames:
        newname = re.sub('-deployment', '', deployname)
        if newname in blacklist:continue
        data = {}
        for kubeid, deploylist in deploydict.items():
            if deploylist.get(deployname, None):
                data[kubeid] = deploylist.get(deployname, '-')
        if len(list(set(data.values()))) !=1:
            data['diff'] = 1
        elif str(samehide) == str(1):
            continue
        data['name'] = deployname
        datas.append(data)
    return datas

def get_imagediff_table_label():
    config = get_config_by_group(group='imagediff')
    data = [{'label': 'Deployment', 'prop': 'name'}]
    kubes = config.get('kubes', '')
    for kubeid in kubes.split(','):
        kubeobj = Kubernetes.objects.get(id=kubeid)
        kubename = kubeobj.name
        data.append({'label': kubename, 'prop': kubeid})
    return data



def proxy_request_handle(url, method='get', headers={}, body={}, response_key=None):
    response = requests.request(url=url, method=method, data=body, headers=headers)
    # json.dumps('',ensure_ascii=True)
    if response.status_code == 200:
        if not response_key:
            return {'data': response.json()}
        response_key_list = response_key.split('__',1)
        if len(response_key_list) == 1:
            a = response_key_list[0]
            if a == 'cookies':
                response_key_value = dict(response.cookies)
            elif a == 'body':
                response_key_value = response.json()
            else:
                response_key_value = None
        else:
            a, b = response_key_list
            if a == 'cookies':
                response_key_value = response.cookies.get(b)
            elif a == 'body':
                response_key_value = response.json().get(b)
            else:
                response_key_value = None
        if response_key_value == None:
            return False, '未匹配到相关key'
        else:
            return True, response_key_value
    else:
        return False, "返回状态码异常{}".format(response.status_code)